import type { UnwrapRef } from 'vue'
import { ref } from 'vue'

// 在最外层请求，方便data 和 loading直接给到模板
export function useFetch<T>(asyncFn: (parmas?: any) => Promise<T>, immediate = false, initValue?: T) {
  const loading = ref(false)
  const data = ref(initValue)
  const error = ref(null)
  const execute = async function (parmas?: any) {
    loading.value = true
    error.value = null
    try {
      const res = await asyncFn(parmas)
      data.value = res as UnwrapRef<T>
      loading.value = false
    }
    catch (err: any) {
      error.value = err
      loading.value = false
    }
  }

  if (immediate)
    execute()

  return {
    loading,
    data,
    error,
    execute,
  }
}
